//
//  AuthorizationCenter.swift
//  iPhone
//
//  Created by Toj on 11/1/22.
//

import UIKit
import AppTrackingTransparency
import AdSupport

open class AuthorizationManager: NSObject {
    
    public static let manager = AuthorizationManager()
    
    // 本地推送消息权限
    public private(set) var at_isLocalNotificationAuth = false
    // 远程推送消息权限
    public private(set) var at_isRemoteNotificationAuth = false
    
    // 广告权限
    // Adjust 底层也是调用苹果的权限
    // Adjust.requestTrackingAuthorization { (status) in }
    private(set) var at_trackingStatus: ATTrackingAuthorizationStatus = .notDetermined
    // 广告标识符IDFA
    private(set) var at_trackingIDFA: String = ""

    public var at_isTrackingAuth: Bool {
        if #available(iOS 14, *) {
            // 不能用IDFA做判断, 如果没权限IDFA是【0000-0000-0000....】
            return at_trackingStatus == .authorized
        }
        return !at_trackingIDFA.isEmpty // 不确定没权限IDFA是【0000-0000-0000....】
    }
}

public extension AuthorizationManager {
    // 打开Setting 界面
    func openSettings() {
        guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
        let application = UIApplication.shared
        if !application.canOpenURL(url) { return }
        // true : 表示如果没有安装这个APP的话, 那么就返回失败, 无法打开
        // false: 表示如果没有安装这个APP的话, 会在safari中访问这个url
        application.open(url, options: [.universalLinksOnly: false]) { isOpened in
            // print("-->toj: isOpened:\(isOpened)")
        }
    }
}

/**
 * 广告追踪权限
 * Key: true
 * InfoPlistKey文件: 广告权限
 */
public extension AuthorizationManager {
    
    func at_requestTrackingAuthorization(completion: ((_ status: ATTrackingAuthorizationStatus) -> Void)? = nil) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                let status_ = status.at_status
                // print("-->toj: Tracking status: \(status.rawValue)")
                self.at_trackingStatus = status_
                self.at_trackingIDFA = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                completion?(status_)
            }
            return
        }
        at_trackingIDFA = ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
}

/**
 * 推送通知
 */
public extension AuthorizationManager {
    
    // 注册远程推送通知 & 获取状态
    func at_registerPushNotifications() {
        at_registerForRemoteNotifications()
        at_registerLocalNotifications()
    }
    
    // 注册远程推送通知
    func at_registerForRemoteNotifications() {
        let application = UIApplication.shared
        if application.isRegisteredForRemoteNotifications { return }
        application.registerForRemoteNotifications()
    }
    
    // 获取远程通知状态
    func at_getNotificationSettings(completion: ((_ isAllow: Bool) -> Void)? = nil) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) in
            // 如果授权状态是notDetermined: 那其他所有的setting都是0
            // 如果授权状态是deny: 那所有其他的setting都是1
            // 如果授权状态是authorized: 其他设置的值才有意义
            let isAllow = settings.authorizationStatus == .authorized
            self.at_isRemoteNotificationAuth = isAllow
            // print("-->toj: Remote Auth: \(isAllow), thread:\(Thread.current)")
            DispatchQueue.main.async {
                completion?(isAllow)
            }
        })
    }
    
    // 注册本地推送通知
    func at_registerLocalNotifications() {
        let center = UNUserNotificationCenter.current()
        center.delegate = UNCenterManager.manager
        
        let options: UNAuthorizationOptions = [.alert, .badge, .sound]
        center.requestAuthorization(options: options) { isAllow, error in
            self.at_isLocalNotificationAuth = isAllow
            // print("-->toj: Local Auth: \(isAllow)")
        }
    }
}
